package com.zdya.combatdocuments.util;

import lombok.Data;
import org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.ByteArrayInputStream;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class Sm2Util {

    public static void main(String[] args) {
        String certStr = "MIICpTCCAkmgAwIBAgIFAQABwfMwDAYIKoEcz1UBg3UFADCBgDELMAkGA1UEBhMCQ04xDjAMBgNVBAgMBUh1bmFuMREwDwYDVQQHDAhDaGFuZ3NoYTEvMC0GA1UECgwmRG9uZ0ZhbmcgRWxlY3Ryb25pYyBDZXJ0aWZpY2F0ZSBDZW50ZXIxHTAbBgNVBAMMFERGQ0EgUHViaWxjIFJvb3QgU00yMB4XDTIwMDcyODAxMzM1NVoXDTIyMDcyODAxMzM1NVowfjELMAkGA1UEBhMCQ04xDzANBgNVBAgMBuays+WNlzEPMA0GA1UEBwwG6YOR5beeMRMwEQYDVQQKDApodXl1YW56aGFvMSQwIgYDVQQLDBvkuK3nm77kupHlronkuqflk4HnoJTlj5Hpg6gxEjAQBgNVBAMMCeWRvOa6kOaLmzBZMBMGByqGSM49AgEGCCqBHM9VAYItA0IABKVmX4BFuDGlgEjjoEJ5T6HWTmn+VrdpcThsIrwfQL8AD+3Cwd3QVOkU1/CXQtlPGDB8WPunalYT+5U3yV22Byyjga4wgaswDAYEKgMEBwQEMTA0MTAJBgNVHRMEAjAAMB0GA1UdDgQWBBTG+VDDcWkgYKiAD6pgFmsV7vd9DDAfBgNVHSMEGDAWgBSRtCF+BOhCPf/cLPMG9ZMZSteOcjBABgNVHR8EOTA3MDWgM6Axhi9odHRwOi8vcHVibGljLnRvcG9uZWNhLmNvbTo4NDQ2L2xkYXAvc20yY3JsLmNybDAOBgNVHQ8BAf8EBAMCBsAwDAYIKoEcz1UBg3UFAANIADBFAiB//Cwa25HS+Hq6ZJ335mxeGrXtk+dgdkLU66L4vKZ4GgIhAIHemgJBYlJD5Q9Xh4XZvbZNoZhu/ms2WHv9elMq/+bw";
        String plaintext = "123456";
        String temp = "MEQCIG5X+WkhqCJWM+SU2Uu1bNVNH08nJqlhBfFCxqY05QNLAiAexLa+LnT9wdgNikR9YJ3g8CuHgQdzY4/5xVl54D0Ybw1==";



        VerifyResult vr= sm2VerifySignedData(temp,certStr,plaintext);
        System.out.println(vr.isSuccess());
        System.out.println(vr.getReason());
        System.out.println(vr.getUsername());
        System.out.println(vr.getSn());

    }






    /**
     *sm2对签名后的数据进行验签
     * @param sign 签名产生签名值
     * @param certKey 证书串，及公钥
     * @param text 签名原文
     * @return
     */
    public static VerifyResult sm2VerifySignedData(String sign , String certKey, String text){
        VerifyResult vr = new VerifyResult();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            byte[] rs = Base64.getDecoder().decode(sign);
            CertificateFactory factory = new CertificateFactory();
            X509Certificate certificate = (X509Certificate) factory.engineGenerateCertificate(new ByteArrayInputStream(Base64.getDecoder().decode(certKey)));
            // 验证签名
            Signature signature = Signature.getInstance(certificate.getSigAlgName(), new BouncyCastleProvider());
            signature.initVerify(certificate);
            signature.update(text.getBytes("GBK"));
            boolean ver = signature.verify(rs);
            String dn  = certificate.getSubjectDN().toString();
            String sn  = certificate.getSerialNumber().toString(16);
            String[] ss = dn.split(",");
            for (int i = 0; i < ss.length; i++) {
                String s1 = ss[i];
                if(s1.contains("O=")){
                   String username =  s1.split("=")[1];
                   vr.setUsername(username);
                   break;
                }
            }
            vr.setSn(sn);
            vr.setSuccess(ver);
            vr.setReason("验证成功");
            return vr;

        }catch (Exception e){
            vr.setSuccess(false);
            vr.setReason("验证失败");
            return vr;
        }
    }

    @Data
    public static class VerifyResult{
        private boolean success;
        private String reason;
        private String username;
        private String sn;
    }
}
